package com.fsp.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.fsp.pojo.Department;
import com.fsp.pojo.User;
import com.fsp.service.DepartmentService;
import com.fsp.service.UserService;
import com.fsp.vo.PageParam;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @author fushengping
 * @className HelloController
 * @description
 * @date 2021/12/6 14:05
 */
@Controller
@Slf4j
public class HelloController {

    @Autowired
    private UserService userService;
    @Autowired
    private DepartmentService departmentService;

    @GetMapping("/")
    public String hello(Map<String,Object> map){
        // 获取全部用户
        List<User> users = userService.listUsers();
        users.forEach(user -> {
            //通过user表中用户对应的部门id查询所属部门
            Department department = departmentService.getById(user.getDeptId());
            user.setDepartment(department);
        });
        map.put("users",users);
        return "index";
    }

    /**
     * 导入
     */
    @PostMapping("/importExcel")
    public String importExcel(MultipartFile file) throws Exception {
        if (ObjectUtils.isEmpty(file) || file.getSize() == 0){
            return "redirect:/";
        }
        log.info("接收到文件：{}",file.getOriginalFilename());
        // 参数1：文件流
        InputStream stream = file.getInputStream();

        // 参数2：导入类型
        ImportParams params = new ImportParams();

        // 标题占用多少行
        params.setTitleRows(1);

        // 头部属性占用多少行
        params.setHeadRows(1);

        // 从指定的sheet的下标开始读取
        // params.setStartSheetIndex(1);

        // 读取sheet的数量，需要和上面的配合
        // params.setSheetNum(1);

        // 对Excle进行合法参数校验
        params.setImportFields(new String[]{"姓名","部门"});

        List<User> users  = ExcelImportUtil.importExcel(stream, User.class,params);
        // 遍历结果，插入到数据库
        users.forEach(user -> {
            //builder创建者模式,即这里的Department只放入DeptName这一个属性(实体映射类上需加@Builder注解)
            Department build = Department.builder().deptName(user.getDepartment().getDeptName()).build();
            log.info("build为{}",build);
            //通过DeptName查询部门数据，从而获得部门id
            List<Department> departments = departmentService.listDepartments(build.getDeptName());
            if (departments.size() > 0){
                user.setDeptId(departments.get(0).getDeptId());
            }
            userService.insert(user);
        });
        log.info("导入用户：{}",users);
        return "redirect:/";
    }

    /**
     * 导出Excel
     */
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) throws IOException {
        response.setHeader("content-disposition",
                "attachment;fileName="+ URLEncoder.encode("用户列表.xls","UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        // 查询所有用户
        List<User> users = userService.listUsers();
        users.forEach(user -> {
            Department department = departmentService.getById(user.getDeptId());
            user.setDepartment(department);
        });
        // 生成文件的信息
        ExportParams params = new ExportParams();
        params.setTitle("导出的用户信息");
        params.setSheetName("用户信息");

        Workbook workbook = ExcelExportUtil.exportExcel(params, User.class, users);

        // 输出
        workbook.write(outputStream);

        // 关闭资源
        outputStream.close();
        workbook.close();
    }

    @PostMapping("/pageandinfo")
    @ResponseBody
    public PageInfo<User> page(@RequestBody PageParam pageParam) {
        //传入当前页码和每页个数
        return userService.queryPageInfo(pageParam);
    }
}
